home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / urllib.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  51KB  |  1,840 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Open an arbitrary URL.
  5.  
  6. See the following document for more info on URLs:
  7. "Names and Addresses, URIs, URLs, URNs, URCs", at
  8. http://www.w3.org/pub/WWW/Addressing/Overview.html
  9.  
  10. See also the HTTP spec (from which the error codes are derived):
  11. "HTTP - Hypertext Transfer Protocol", at
  12. http://www.w3.org/pub/WWW/Protocols/
  13.  
  14. Related standards and specs:
  15. - RFC1808: the "relative URL" spec. (authoritative status)
  16. - RFC1738 - the "URL standard". (authoritative status)
  17. - RFC1630 - the "URI spec". (informational status)
  18.  
  19. The object returned by URLopener().open(file) will differ per
  20. protocol.  All you know is that is has methods read(), readline(),
  21. readlines(), fileno(), close() and info().  The read*(), fileno()
  22. and close() methods work like those of open files.
  23. The info() method returns a mimetools.Message object which can be
  24. used to query various info about the object, if available.
  25. (mimetools.Message objects are queried with the getheader() method.)
  26. '''
  27. import string
  28. import socket
  29. import os
  30. import time
  31. import sys
  32. from urlparse import urljoin as basejoin
  33. import warnings
  34. __all__ = [
  35.     'urlopen',
  36.     'URLopener',
  37.     'FancyURLopener',
  38.     'urlretrieve',
  39.     'urlcleanup',
  40.     'quote',
  41.     'quote_plus',
  42.     'unquote',
  43.     'unquote_plus',
  44.     'urlencode',
  45.     'url2pathname',
  46.     'pathname2url',
  47.     'splittag',
  48.     'localhost',
  49.     'thishost',
  50.     'ftperrors',
  51.     'basejoin',
  52.     'unwrap',
  53.     'splittype',
  54.     'splithost',
  55.     'splituser',
  56.     'splitpasswd',
  57.     'splitport',
  58.     'splitnport',
  59.     'splitquery',
  60.     'splitattr',
  61.     'splitvalue',
  62.     'getproxies']
  63. __version__ = '1.17'
  64. MAXFTPCACHE = 10
  65. if os.name == 'mac':
  66.     from macurl2path import url2pathname, pathname2url
  67. elif os.name == 'nt':
  68.     from nturl2path import url2pathname, pathname2url
  69. elif os.name == 'riscos':
  70.     from rourl2path import url2pathname, pathname2url
  71. else:
  72.     
  73.     def url2pathname(pathname):
  74.         """OS-specific conversion from a relative URL of the 'file' scheme
  75.         to a file system path; not recommended for general use."""
  76.         return unquote(pathname)
  77.  
  78.     
  79.     def pathname2url(pathname):
  80.         """OS-specific conversion from a file system path to a relative URL
  81.         of the 'file' scheme; not recommended for general use."""
  82.         return quote(pathname)
  83.  
  84. _urlopener = None
  85.  
  86. def urlopen(url, data = None, proxies = None):
  87.     '''Create a file-like object for the specified URL to read from.'''
  88.     global _urlopener
  89.     warnpy3k = warnpy3k
  90.     import warnings
  91.     warnings.warnpy3k('urllib.urlopen() has been removed in Python 3.0 in favor of urllib2.urlopen()', stacklevel = 2)
  92.     if proxies is not None:
  93.         opener = FancyURLopener(proxies = proxies)
  94.     elif not _urlopener:
  95.         opener = FancyURLopener()
  96.         _urlopener = opener
  97.     else:
  98.         opener = _urlopener
  99.     if data is None:
  100.         return opener.open(url)
  101.     return opener.open(url, data)
  102.  
  103.  
  104. def urlretrieve(url, filename = None, reporthook = None, data = None):
  105.     global _urlopener
  106.     if not _urlopener:
  107.         _urlopener = FancyURLopener()
  108.     
  109.     return _urlopener.retrieve(url, filename, reporthook, data)
  110.  
  111.  
  112. def urlcleanup():
  113.     if _urlopener:
  114.         _urlopener.cleanup()
  115.     
  116.  
  117.  
  118. try:
  119.     import ssl
  120. except:
  121.     _have_ssl = False
  122.  
  123. _have_ssl = True
  124.  
  125. class ContentTooShortError(IOError):
  126.     
  127.     def __init__(self, message, content):
  128.         IOError.__init__(self, message)
  129.         self.content = content
  130.  
  131.  
  132. ftpcache = { }
  133.  
  134. class URLopener:
  135.     """Class to open URLs.
  136.     This is a class rather than just a subroutine because we may need
  137.     more than one set of global protocol-specific options.
  138.     Note -- this is a base class for those who don't want the
  139.     automatic handling of errors type 302 (relocated) and 401
  140.     (authorization needed)."""
  141.     __tempfiles = None
  142.     version = 'Python-urllib/%s' % __version__
  143.     
  144.     def __init__(self, proxies = None, **x509):
  145.         if proxies is None:
  146.             proxies = getproxies()
  147.         
  148.         if not hasattr(proxies, 'has_key'):
  149.             raise AssertionError, 'proxies must be a mapping'
  150.         self.proxies = proxies
  151.         self.key_file = x509.get('key_file')
  152.         self.cert_file = x509.get('cert_file')
  153.         self.addheaders = [
  154.             ('User-Agent', self.version)]
  155.         self._URLopener__tempfiles = []
  156.         self._URLopener__unlink = os.unlink
  157.         self.tempcache = None
  158.         self.ftpcache = ftpcache
  159.  
  160.     
  161.     def __del__(self):
  162.         self.close()
  163.  
  164.     
  165.     def close(self):
  166.         self.cleanup()
  167.  
  168.     
  169.     def cleanup(self):
  170.         if self._URLopener__tempfiles:
  171.             for file in self._URLopener__tempfiles:
  172.                 
  173.                 try:
  174.                     self._URLopener__unlink(file)
  175.                 continue
  176.                 except OSError:
  177.                     continue
  178.                 
  179.  
  180.             
  181.             del self._URLopener__tempfiles[:]
  182.         
  183.         if self.tempcache:
  184.             self.tempcache.clear()
  185.         
  186.  
  187.     
  188.     def addheader(self, *args):
  189.         """Add a header to be used by the HTTP interface only
  190.         e.g. u.addheader('Accept', 'sound/basic')"""
  191.         self.addheaders.append(args)
  192.  
  193.     
  194.     def open(self, fullurl, data = None):
  195.         """Use URLopener().open(file) instead of open(file, 'r')."""
  196.         fullurl = unwrap(toBytes(fullurl))
  197.         fullurl = quote(fullurl, safe = "%/:=&?~#+!$,;'@()*[]")
  198.         if self.tempcache and fullurl in self.tempcache:
  199.             (filename, headers) = self.tempcache[fullurl]
  200.             fp = open(filename, 'rb')
  201.             return addinfourl(fp, headers, fullurl)
  202.         (urltype, url) = splittype(fullurl)
  203.         if not urltype:
  204.             urltype = 'file'
  205.         
  206.         if urltype in self.proxies:
  207.             proxy = self.proxies[urltype]
  208.             (urltype, proxyhost) = splittype(proxy)
  209.             (host, selector) = splithost(proxyhost)
  210.             url = (host, fullurl)
  211.         else:
  212.             proxy = None
  213.         name = 'open_' + urltype
  214.         self.type = urltype
  215.         name = name.replace('-', '_')
  216.         if not hasattr(self, name):
  217.             if proxy:
  218.                 return self.open_unknown_proxy(proxy, fullurl, data)
  219.             return self.open_unknown(fullurl, data)
  220.         hasattr(self, name)
  221.         
  222.         try:
  223.             if data is None:
  224.                 return getattr(self, name)(url)
  225.             return getattr(self, name)(url, data)
  226.         except socket.error:
  227.             msg = None
  228.             raise IOError, ('socket error', msg), sys.exc_info()[2]
  229.  
  230.  
  231.     
  232.     def open_unknown(self, fullurl, data = None):
  233.         '''Overridable interface to open unknown URL type.'''
  234.         (type, url) = splittype(fullurl)
  235.         raise IOError, ('url error', 'unknown url type', type)
  236.  
  237.     
  238.     def open_unknown_proxy(self, proxy, fullurl, data = None):
  239.         '''Overridable interface to open unknown URL type.'''
  240.         (type, url) = splittype(fullurl)
  241.         raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
  242.  
  243.     
  244.     def retrieve(self, url, filename = None, reporthook = None, data = None):
  245.         '''retrieve(url) returns (filename, headers) for a local object
  246.         or (tempfilename, headers) for a remote object.'''
  247.         url = unwrap(toBytes(url))
  248.         if self.tempcache and url in self.tempcache:
  249.             return self.tempcache[url]
  250.         (type, url1) = splittype(url)
  251.         if filename is None:
  252.             if not type or type == 'file':
  253.                 
  254.                 try:
  255.                     fp = self.open_local_file(url1)
  256.                     hdrs = fp.info()
  257.                     del fp
  258.                     return (url2pathname(splithost(url1)[1]), hdrs)
  259.                 except IOError:
  260.                     url in self.tempcache
  261.                     msg = url in self.tempcache
  262.                 except:
  263.                     url in self.tempcache<EXCEPTION MATCH>IOError
  264.                 
  265.  
  266.         url in self.tempcache
  267.         fp = self.open(url, data)
  268.         
  269.         try:
  270.             headers = fp.info()
  271.             if filename:
  272.                 tfp = open(filename, 'wb')
  273.             else:
  274.                 import tempfile as tempfile
  275.                 (garbage, path) = splittype(url)
  276.                 if not path:
  277.                     pass
  278.                 (garbage, path) = splithost('')
  279.                 if not path:
  280.                     pass
  281.                 (path, garbage) = splitquery('')
  282.                 if not path:
  283.                     pass
  284.                 (path, garbage) = splitattr('')
  285.                 suffix = os.path.splitext(path)[1]
  286.                 (fd, filename) = tempfile.mkstemp(suffix)
  287.                 self._URLopener__tempfiles.append(filename)
  288.                 tfp = os.fdopen(fd, 'wb')
  289.             
  290.             try:
  291.                 result = (filename, headers)
  292.                 if self.tempcache is not None:
  293.                     self.tempcache[url] = result
  294.                 
  295.                 bs = 8192
  296.                 size = -1
  297.                 read = 0
  298.                 blocknum = 0
  299.                 if reporthook:
  300.                     if 'content-length' in headers:
  301.                         size = int(headers['Content-Length'])
  302.                     
  303.                     reporthook(blocknum, bs, size)
  304.                 
  305.                 while None:
  306.                     block = fp.read(bs)
  307.                     if block == '':
  308.                         break
  309.                     
  310.                     read += len(block)
  311.                     blocknum += 1
  312.                     if reporthook:
  313.                         reporthook(blocknum, bs, size)
  314.                         continue
  315.                 tfp.close()
  316.             finally:
  317.                 fp.close()
  318.  
  319.             del fp
  320.             del tfp
  321.             if size >= 0 and read < size:
  322.                 raise ContentTooShortError('retrieval incomplete: got only %i out of %i bytes' % (read, size), result)
  323.             read < size
  324.             return result
  325.  
  326.  
  327.     
  328.     def open_http(self, url, data = None):
  329.         '''Use HTTP protocol.'''
  330.         import httplib as httplib
  331.         user_passwd = None
  332.         proxy_passwd = None
  333.         if isinstance(url, str):
  334.             (host, selector) = splithost(url)
  335.             if host:
  336.                 (user_passwd, host) = splituser(host)
  337.                 host = unquote(host)
  338.             
  339.             realhost = host
  340.         else:
  341.             (host, selector) = url
  342.             (proxy_passwd, host) = splituser(host)
  343.             (urltype, rest) = splittype(selector)
  344.             url = rest
  345.             user_passwd = None
  346.             if urltype.lower() != 'http':
  347.                 realhost = None
  348.             else:
  349.                 (realhost, rest) = splithost(rest)
  350.                 if realhost:
  351.                     (user_passwd, realhost) = splituser(realhost)
  352.                 
  353.                 if user_passwd:
  354.                     selector = '%s://%s%s' % (urltype, realhost, rest)
  355.                 
  356.                 if proxy_bypass(realhost):
  357.                     host = realhost
  358.                 
  359.         if not host:
  360.             raise IOError, ('http error', 'no host given')
  361.         host
  362.         if proxy_passwd:
  363.             import base64 as base64
  364.             proxy_auth = base64.b64encode(proxy_passwd).strip()
  365.         else:
  366.             proxy_auth = None
  367.         if user_passwd:
  368.             import base64 as base64
  369.             auth = base64.b64encode(user_passwd).strip()
  370.         else:
  371.             auth = None
  372.         h = httplib.HTTP(host)
  373.         if data is not None:
  374.             h.putrequest('POST', selector)
  375.             h.putheader('Content-Type', 'application/x-www-form-urlencoded')
  376.             h.putheader('Content-Length', '%d' % len(data))
  377.         else:
  378.             h.putrequest('GET', selector)
  379.         if proxy_auth:
  380.             h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
  381.         
  382.         if auth:
  383.             h.putheader('Authorization', 'Basic %s' % auth)
  384.         
  385.         if realhost:
  386.             h.putheader('Host', realhost)
  387.         
  388.         for args in self.addheaders:
  389.             h.putheader(*args)
  390.         
  391.         h.endheaders()
  392.         if data is not None:
  393.             h.send(data)
  394.         
  395.         (errcode, errmsg, headers) = h.getreply()
  396.         fp = h.getfile()
  397.         if errcode == -1:
  398.             if fp:
  399.                 fp.close()
  400.             
  401.             raise IOError, ('http protocol error', 0, 'got a bad status line', None)
  402.         errcode == -1
  403.         if errcode <= errcode:
  404.             pass
  405.         elif errcode < 300:
  406.             return addinfourl(fp, headers, 'http:' + url, errcode)
  407.         if data is None:
  408.             return self.http_error(url, fp, errcode, errmsg, headers)
  409.         return self.http_error(url, fp, errcode, errmsg, headers, data)
  410.  
  411.     
  412.     def http_error(self, url, fp, errcode, errmsg, headers, data = None):
  413.         '''Handle http errors.
  414.         Derived class can override this, or provide specific handlers
  415.         named http_error_DDD where DDD is the 3-digit error code.'''
  416.         name = 'http_error_%d' % errcode
  417.         if hasattr(self, name):
  418.             method = getattr(self, name)
  419.             if data is None:
  420.                 result = method(url, fp, errcode, errmsg, headers)
  421.             else:
  422.                 result = method(url, fp, errcode, errmsg, headers, data)
  423.             if result:
  424.                 return result
  425.         
  426.         return self.http_error_default(url, fp, errcode, errmsg, headers)
  427.  
  428.     
  429.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  430.         '''Default error handler: close the connection and raise IOError.'''
  431.         void = fp.read()
  432.         fp.close()
  433.         raise IOError, ('http error', errcode, errmsg, headers)
  434.  
  435.     if _have_ssl:
  436.         
  437.         def open_https(self, url, data = None):
  438.             '''Use HTTPS protocol.'''
  439.             import httplib
  440.             user_passwd = None
  441.             proxy_passwd = None
  442.             if isinstance(url, str):
  443.                 (host, selector) = splithost(url)
  444.                 if host:
  445.                     (user_passwd, host) = splituser(host)
  446.                     host = unquote(host)
  447.                 
  448.                 realhost = host
  449.             else:
  450.                 (host, selector) = url
  451.                 (proxy_passwd, host) = splituser(host)
  452.                 (urltype, rest) = splittype(selector)
  453.                 url = rest
  454.                 user_passwd = None
  455.                 if urltype.lower() != 'https':
  456.                     realhost = None
  457.                 else:
  458.                     (realhost, rest) = splithost(rest)
  459.                     if realhost:
  460.                         (user_passwd, realhost) = splituser(realhost)
  461.                     
  462.                     if user_passwd:
  463.                         selector = '%s://%s%s' % (urltype, realhost, rest)
  464.                     
  465.             if not host:
  466.                 raise IOError, ('https error', 'no host given')
  467.             host
  468.             if proxy_passwd:
  469.                 import base64
  470.                 proxy_auth = base64.b64encode(proxy_passwd).strip()
  471.             else:
  472.                 proxy_auth = None
  473.             if user_passwd:
  474.                 import base64
  475.                 auth = base64.b64encode(user_passwd).strip()
  476.             else:
  477.                 auth = None
  478.             h = httplib.HTTPS(host, 0, key_file = self.key_file, cert_file = self.cert_file)
  479.             if data is not None:
  480.                 h.putrequest('POST', selector)
  481.                 h.putheader('Content-Type', 'application/x-www-form-urlencoded')
  482.                 h.putheader('Content-Length', '%d' % len(data))
  483.             else:
  484.                 h.putrequest('GET', selector)
  485.             if proxy_auth:
  486.                 h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
  487.             
  488.             if auth:
  489.                 h.putheader('Authorization', 'Basic %s' % auth)
  490.             
  491.             if realhost:
  492.                 h.putheader('Host', realhost)
  493.             
  494.             for args in self.addheaders:
  495.                 h.putheader(*args)
  496.             
  497.             h.endheaders()
  498.             if data is not None:
  499.                 h.send(data)
  500.             
  501.             (errcode, errmsg, headers) = h.getreply()
  502.             fp = h.getfile()
  503.             if errcode == -1:
  504.                 if fp:
  505.                     fp.close()
  506.                 
  507.                 raise IOError, ('http protocol error', 0, 'got a bad status line', None)
  508.             errcode == -1
  509.             if errcode <= errcode:
  510.                 pass
  511.             elif errcode < 300:
  512.                 return addinfourl(fp, headers, 'https:' + url, errcode)
  513.             if data is None:
  514.                 return self.http_error(url, fp, errcode, errmsg, headers)
  515.             return self.http_error(url, fp, errcode, errmsg, headers, data)
  516.  
  517.     
  518.     
  519.     def open_file(self, url):
  520.         '''Use local file or FTP depending on form of URL.'''
  521.         if not isinstance(url, str):
  522.             raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
  523.         isinstance(url, str)
  524.         if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
  525.             return self.open_ftp(url)
  526.         return self.open_local_file(url)
  527.  
  528.     
  529.     def open_local_file(self, url):
  530.         '''Use local file.'''
  531.         import mimetypes as mimetypes
  532.         import mimetools as mimetools
  533.         import email.utils as email
  534.         
  535.         try:
  536.             StringIO = StringIO
  537.             import cStringIO
  538.         except ImportError:
  539.             StringIO = StringIO
  540.             import StringIO
  541.  
  542.         (host, file) = splithost(url)
  543.         localname = url2pathname(file)
  544.         
  545.         try:
  546.             stats = os.stat(localname)
  547.         except OSError:
  548.             e = None
  549.             raise IOError(e.errno, e.strerror, e.filename)
  550.  
  551.         size = stats.st_size
  552.         modified = email.utils.formatdate(stats.st_mtime, usegmt = True)
  553.         mtype = mimetypes.guess_type(url)[0]
  554.         if not mtype:
  555.             pass
  556.         headers = mimetools.Message(StringIO('Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % ('text/plain', size, modified)))
  557.         if not host:
  558.             urlfile = file
  559.             if file[:1] == '/':
  560.                 urlfile = 'file://' + file
  561.             
  562.             return addinfourl(open(localname, 'rb'), headers, urlfile)
  563.         (host, port) = splitport(host)
  564.         if not port and socket.gethostbyname(host) in (localhost(), thishost()):
  565.             urlfile = file
  566.             if file[:1] == '/':
  567.                 urlfile = 'file://' + file
  568.             
  569.             return addinfourl(open(localname, 'rb'), headers, urlfile)
  570.         raise IOError, ('local file error', 'not on local host')
  571.  
  572.     
  573.     def open_ftp(self, url):
  574.         '''Use FTP protocol.'''
  575.         if not isinstance(url, str):
  576.             raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
  577.         isinstance(url, str)
  578.         import mimetypes
  579.         import mimetools
  580.         
  581.         try:
  582.             StringIO = StringIO
  583.             import cStringIO
  584.         except ImportError:
  585.             StringIO = StringIO
  586.             import StringIO
  587.  
  588.         (host, path) = splithost(url)
  589.         if not host:
  590.             raise IOError, ('ftp error', 'no host given')
  591.         host
  592.         (host, port) = splitport(host)
  593.         (user, host) = splituser(host)
  594.         if user:
  595.             (user, passwd) = splitpasswd(user)
  596.         else:
  597.             passwd = None
  598.         host = unquote(host)
  599.         if not user:
  600.             pass
  601.         user = unquote('')
  602.         if not passwd:
  603.             pass
  604.         passwd = unquote('')
  605.         host = socket.gethostbyname(host)
  606.         if not port:
  607.             import ftplib as ftplib
  608.             port = ftplib.FTP_PORT
  609.         else:
  610.             port = int(port)
  611.         (path, attrs) = splitattr(path)
  612.         path = unquote(path)
  613.         dirs = path.split('/')
  614.         dirs = dirs[:-1]
  615.         file = dirs[-1]
  616.         if dirs and not dirs[0]:
  617.             dirs = dirs[1:]
  618.         
  619.         if dirs and not dirs[0]:
  620.             dirs[0] = '/'
  621.         
  622.         key = (user, host, port, '/'.join(dirs))
  623.         if len(self.ftpcache) > MAXFTPCACHE:
  624.             for k in self.ftpcache.keys():
  625.                 if k != key:
  626.                     v = self.ftpcache[k]
  627.                     del self.ftpcache[k]
  628.                     v.close()
  629.                     continue
  630.             
  631.         
  632.         
  633.         try:
  634.             if key not in self.ftpcache:
  635.                 self.ftpcache[key] = ftpwrapper(user, passwd, host, port, dirs)
  636.             
  637.             if not file:
  638.                 type = 'D'
  639.             else:
  640.                 type = 'I'
  641.             for attr in attrs:
  642.                 (attr, value) = splitvalue(attr)
  643.                 if attr.lower() == 'type' and value in ('a', 'A', 'i', 'I', 'd', 'D'):
  644.                     type = value.upper()
  645.                     continue
  646.             
  647.             (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
  648.             mtype = mimetypes.guess_type('ftp:' + url)[0]
  649.             headers = ''
  650.             if mtype:
  651.                 headers += 'Content-Type: %s\n' % mtype
  652.             
  653.             if retrlen is not None and retrlen >= 0:
  654.                 headers += 'Content-Length: %d\n' % retrlen
  655.             
  656.             headers = mimetools.Message(StringIO(headers))
  657.             return addinfourl(fp, headers, 'ftp:' + url)
  658.         except ftperrors():
  659.             msg = None
  660.             raise IOError, ('ftp error', msg), sys.exc_info()[2]
  661.  
  662.  
  663.     
  664.     def open_data(self, url, data = None):
  665.         '''Use "data" URL.'''
  666.         if not isinstance(url, str):
  667.             raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
  668.         isinstance(url, str)
  669.         import mimetools
  670.         
  671.         try:
  672.             StringIO = StringIO
  673.             import cStringIO
  674.         except ImportError:
  675.             StringIO = StringIO
  676.             import StringIO
  677.  
  678.         
  679.         try:
  680.             (type, data) = url.split(',', 1)
  681.         except ValueError:
  682.             raise IOError, ('data error', 'bad data URL')
  683.  
  684.         if not type:
  685.             type = 'text/plain;charset=US-ASCII'
  686.         
  687.         semi = type.rfind(';')
  688.         if semi >= 0 and '=' not in type[semi:]:
  689.             encoding = type[semi + 1:]
  690.             type = type[:semi]
  691.         else:
  692.             encoding = ''
  693.         msg = []
  694.         msg.append('Date: %s' % time.strftime('%a, %d %b %Y %T GMT', time.gmtime(time.time())))
  695.         msg.append('Content-type: %s' % type)
  696.         if encoding == 'base64':
  697.             import base64
  698.             data = base64.decodestring(data)
  699.         else:
  700.             data = unquote(data)
  701.         msg.append('Content-Length: %d' % len(data))
  702.         msg.append('')
  703.         msg.append(data)
  704.         msg = '\n'.join(msg)
  705.         f = StringIO(msg)
  706.         headers = mimetools.Message(f, 0)
  707.         return addinfourl(f, headers, url)
  708.  
  709.  
  710.  
  711. class FancyURLopener(URLopener):
  712.     '''Derived class with handlers for errors we can handle (perhaps).'''
  713.     
  714.     def __init__(self, *args, **kwargs):
  715.         URLopener.__init__(self, *args, **kwargs)
  716.         self.auth_cache = { }
  717.         self.tries = 0
  718.         self.maxtries = 10
  719.  
  720.     
  721.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  722.         """Default error handling -- don't raise an exception."""
  723.         return addinfourl(fp, headers, 'http:' + url, errcode)
  724.  
  725.     
  726.     def http_error_302(self, url, fp, errcode, errmsg, headers, data = None):
  727.         '''Error 302 -- relocated (temporarily).'''
  728.         self.tries += 1
  729.         if self.maxtries and self.tries >= self.maxtries:
  730.             if hasattr(self, 'http_error_500'):
  731.                 meth = self.http_error_500
  732.             else:
  733.                 meth = self.http_error_default
  734.             self.tries = 0
  735.             return meth(url, fp, 500, 'Internal Server Error: Redirect Recursion', headers)
  736.         result = self.redirect_internal(url, fp, errcode, errmsg, headers, data)
  737.         self.tries = 0
  738.         return result
  739.  
  740.     
  741.     def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
  742.         if 'location' in headers:
  743.             newurl = headers['location']
  744.         elif 'uri' in headers:
  745.             newurl = headers['uri']
  746.         else:
  747.             return None
  748.         void = ('location' in headers).read()
  749.         fp.close()
  750.         newurl = basejoin(self.type + ':' + url, newurl)
  751.         return self.open(newurl)
  752.  
  753.     
  754.     def http_error_301(self, url, fp, errcode, errmsg, headers, data = None):
  755.         '''Error 301 -- also relocated (permanently).'''
  756.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  757.  
  758.     
  759.     def http_error_303(self, url, fp, errcode, errmsg, headers, data = None):
  760.         '''Error 303 -- also relocated (essentially identical to 302).'''
  761.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  762.  
  763.     
  764.     def http_error_307(self, url, fp, errcode, errmsg, headers, data = None):
  765.         '''Error 307 -- relocated, but turn POST into error.'''
  766.         if data is None:
  767.             return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  768.         return self.http_error_default(url, fp, errcode, errmsg, headers)
  769.  
  770.     
  771.     def http_error_401(self, url, fp, errcode, errmsg, headers, data = None):
  772.         '''Error 401 -- authentication required.
  773.         This function supports Basic authentication only.'''
  774.         if 'www-authenticate' not in headers:
  775.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  776.         
  777.         stuff = headers['www-authenticate']
  778.         import re as re
  779.         match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  780.         if not match:
  781.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  782.         
  783.         (scheme, realm) = match.groups()
  784.         if scheme.lower() != 'basic':
  785.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  786.         
  787.         name = 'retry_' + self.type + '_basic_auth'
  788.         if data is None:
  789.             return getattr(self, name)(url, realm)
  790.         return getattr(self, name)(url, realm, data)
  791.  
  792.     
  793.     def http_error_407(self, url, fp, errcode, errmsg, headers, data = None):
  794.         '''Error 407 -- proxy authentication required.
  795.         This function supports Basic authentication only.'''
  796.         if 'proxy-authenticate' not in headers:
  797.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  798.         
  799.         stuff = headers['proxy-authenticate']
  800.         import re
  801.         match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  802.         if not match:
  803.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  804.         
  805.         (scheme, realm) = match.groups()
  806.         if scheme.lower() != 'basic':
  807.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  808.         
  809.         name = 'retry_proxy_' + self.type + '_basic_auth'
  810.         if data is None:
  811.             return getattr(self, name)(url, realm)
  812.         return getattr(self, name)(url, realm, data)
  813.  
  814.     
  815.     def retry_proxy_http_basic_auth(self, url, realm, data = None):
  816.         (host, selector) = splithost(url)
  817.         newurl = 'http://' + host + selector
  818.         proxy = self.proxies['http']
  819.         (urltype, proxyhost) = splittype(proxy)
  820.         (proxyhost, proxyselector) = splithost(proxyhost)
  821.         i = proxyhost.find('@') + 1
  822.         proxyhost = proxyhost[i:]
  823.         (user, passwd) = self.get_user_passwd(proxyhost, realm, i)
  824.         if not user or passwd:
  825.             return None
  826.         proxyhost = quote(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + proxyhost
  827.         self.proxies['http'] = 'http://' + proxyhost + proxyselector
  828.         if data is None:
  829.             return self.open(newurl)
  830.         return self.open(newurl, data)
  831.  
  832.     
  833.     def retry_proxy_https_basic_auth(self, url, realm, data = None):
  834.         (host, selector) = splithost(url)
  835.         newurl = 'https://' + host + selector
  836.         proxy = self.proxies['https']
  837.         (urltype, proxyhost) = splittype(proxy)
  838.         (proxyhost, proxyselector) = splithost(proxyhost)
  839.         i = proxyhost.find('@') + 1
  840.         proxyhost = proxyhost[i:]
  841.         (user, passwd) = self.get_user_passwd(proxyhost, realm, i)
  842.         if not user or passwd:
  843.             return None
  844.         proxyhost = quote(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + proxyhost
  845.         self.proxies['https'] = 'https://' + proxyhost + proxyselector
  846.         if data is None:
  847.             return self.open(newurl)
  848.         return self.open(newurl, data)
  849.  
  850.     
  851.     def retry_http_basic_auth(self, url, realm, data = None):
  852.         (host, selector) = splithost(url)
  853.         i = host.find('@') + 1
  854.         host = host[i:]
  855.         (user, passwd) = self.get_user_passwd(host, realm, i)
  856.         if not user or passwd:
  857.             return None
  858.         host = quote(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + host
  859.         newurl = 'http://' + host + selector
  860.         if data is None:
  861.             return self.open(newurl)
  862.         return self.open(newurl, data)
  863.  
  864.     
  865.     def retry_https_basic_auth(self, url, realm, data = None):
  866.         (host, selector) = splithost(url)
  867.         i = host.find('@') + 1
  868.         host = host[i:]
  869.         (user, passwd) = self.get_user_passwd(host, realm, i)
  870.         if not user or passwd:
  871.             return None
  872.         host = quote(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + host
  873.         newurl = 'https://' + host + selector
  874.         if data is None:
  875.             return self.open(newurl)
  876.         return self.open(newurl, data)
  877.  
  878.     
  879.     def get_user_passwd(self, host, realm, clear_cache = 0):
  880.         key = realm + '@' + host.lower()
  881.         if key in self.auth_cache:
  882.             if clear_cache:
  883.                 del self.auth_cache[key]
  884.             else:
  885.                 return self.auth_cache[key]
  886.         clear_cache
  887.         (user, passwd) = self.prompt_user_passwd(host, realm)
  888.         if user or passwd:
  889.             self.auth_cache[key] = (user, passwd)
  890.         
  891.         return (user, passwd)
  892.  
  893.     
  894.     def prompt_user_passwd(self, host, realm):
  895.         '''Override this in a GUI environment!'''
  896.         import getpass as getpass
  897.         
  898.         try:
  899.             user = raw_input('Enter username for %s at %s: ' % (realm, host))
  900.             passwd = getpass.getpass('Enter password for %s in %s at %s: ' % (user, realm, host))
  901.             return (user, passwd)
  902.         except KeyboardInterrupt:
  903.             print 
  904.             return (None, None)
  905.  
  906.  
  907.  
  908. _localhost = None
  909.  
  910. def localhost():
  911.     """Return the IP address of the magic hostname 'localhost'."""
  912.     global _localhost
  913.     if _localhost is None:
  914.         _localhost = socket.gethostbyname('localhost')
  915.     
  916.     return _localhost
  917.  
  918. _thishost = None
  919.  
  920. def thishost():
  921.     '''Return the IP address of the current host.'''
  922.     global _thishost
  923.     if _thishost is None:
  924.         _thishost = socket.gethostbyname(socket.gethostname())
  925.     
  926.     return _thishost
  927.  
  928. _ftperrors = None
  929.  
  930. def ftperrors():
  931.     '''Return the set of errors raised by the FTP class.'''
  932.     global _ftperrors
  933.     if _ftperrors is None:
  934.         import ftplib
  935.         _ftperrors = ftplib.all_errors
  936.     
  937.     return _ftperrors
  938.  
  939. _noheaders = None
  940.  
  941. def noheaders():
  942.     '''Return an empty mimetools.Message object.'''
  943.     global _noheaders
  944.     if _noheaders is None:
  945.         import mimetools
  946.         
  947.         try:
  948.             StringIO = StringIO
  949.             import cStringIO
  950.         except ImportError:
  951.             StringIO = StringIO
  952.             import StringIO
  953.  
  954.         _noheaders = mimetools.Message(StringIO(), 0)
  955.         _noheaders.fp.close()
  956.     
  957.     return _noheaders
  958.  
  959.  
  960. class ftpwrapper:
  961.     '''Class used by open_ftp() for cache of open FTP connections.'''
  962.     
  963.     def __init__(self, user, passwd, host, port, dirs, timeout = socket._GLOBAL_DEFAULT_TIMEOUT):
  964.         self.user = user
  965.         self.passwd = passwd
  966.         self.host = host
  967.         self.port = port
  968.         self.dirs = dirs
  969.         self.timeout = timeout
  970.         self.init()
  971.  
  972.     
  973.     def init(self):
  974.         import ftplib
  975.         self.busy = 0
  976.         self.ftp = ftplib.FTP()
  977.         self.ftp.connect(self.host, self.port, self.timeout)
  978.         self.ftp.login(self.user, self.passwd)
  979.         for dir in self.dirs:
  980.             self.ftp.cwd(dir)
  981.         
  982.  
  983.     
  984.     def retrfile(self, file, type):
  985.         import ftplib
  986.         self.endtransfer()
  987.         if type in ('d', 'D'):
  988.             cmd = 'TYPE A'
  989.             isdir = 1
  990.         else:
  991.             cmd = 'TYPE ' + type
  992.             isdir = 0
  993.         
  994.         try:
  995.             self.ftp.voidcmd(cmd)
  996.         except ftplib.all_errors:
  997.             self.init()
  998.             self.ftp.voidcmd(cmd)
  999.  
  1000.         conn = None
  1001.         if file and not isdir:
  1002.             
  1003.             try:
  1004.                 cmd = 'RETR ' + file
  1005.                 conn = self.ftp.ntransfercmd(cmd)
  1006.             except ftplib.error_perm:
  1007.                 reason = None
  1008.                 if str(reason)[:3] != '550':
  1009.                     raise IOError, ('ftp error', reason), sys.exc_info()[2]
  1010.                 str(reason)[:3] != '550'
  1011.             except:
  1012.                 None<EXCEPTION MATCH>ftplib.error_perm
  1013.             
  1014.  
  1015.         None<EXCEPTION MATCH>ftplib.error_perm
  1016.         if not conn:
  1017.             self.ftp.voidcmd('TYPE A')
  1018.             if file:
  1019.                 pwd = self.ftp.pwd()
  1020.                 
  1021.                 try:
  1022.                     self.ftp.cwd(file)
  1023.                 except ftplib.error_perm:
  1024.                     reason = None
  1025.                     raise IOError, ('ftp error', reason), sys.exc_info()[2]
  1026.                 finally:
  1027.                     self.ftp.cwd(pwd)
  1028.  
  1029.                 cmd = 'LIST ' + file
  1030.             else:
  1031.                 cmd = 'LIST'
  1032.             conn = self.ftp.ntransfercmd(cmd)
  1033.         
  1034.         self.busy = 1
  1035.         return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
  1036.  
  1037.     
  1038.     def endtransfer(self):
  1039.         if not self.busy:
  1040.             return None
  1041.         self.busy = 0
  1042.         
  1043.         try:
  1044.             self.ftp.voidresp()
  1045.         except ftperrors():
  1046.             self.busy
  1047.             self.busy
  1048.         except:
  1049.             self.busy
  1050.  
  1051.  
  1052.     
  1053.     def close(self):
  1054.         self.endtransfer()
  1055.         
  1056.         try:
  1057.             self.ftp.close()
  1058.         except ftperrors():
  1059.             pass
  1060.  
  1061.  
  1062.  
  1063.  
  1064. class addbase:
  1065.     '''Base class for addinfo and addclosehook.'''
  1066.     
  1067.     def __init__(self, fp):
  1068.         self.fp = fp
  1069.         self.read = self.fp.read
  1070.         self.readline = self.fp.readline
  1071.         if hasattr(self.fp, 'readlines'):
  1072.             self.readlines = self.fp.readlines
  1073.         
  1074.         if hasattr(self.fp, 'fileno'):
  1075.             self.fileno = self.fp.fileno
  1076.         else:
  1077.             
  1078.             self.fileno = lambda : pass
  1079.         if hasattr(self.fp, '__iter__'):
  1080.             self.__iter__ = self.fp.__iter__
  1081.             if hasattr(self.fp, 'next'):
  1082.                 self.next = self.fp.next
  1083.             
  1084.         
  1085.  
  1086.     
  1087.     def __repr__(self):
  1088.         return '<%s at %r whose fp = %r>' % (self.__class__.__name__, id(self), self.fp)
  1089.  
  1090.     
  1091.     def close(self):
  1092.         self.read = None
  1093.         self.readline = None
  1094.         self.readlines = None
  1095.         self.fileno = None
  1096.         if self.fp:
  1097.             self.fp.close()
  1098.         
  1099.         self.fp = None
  1100.  
  1101.  
  1102.  
  1103. class addclosehook(addbase):
  1104.     '''Class to add a close hook to an open file.'''
  1105.     
  1106.     def __init__(self, fp, closehook, *hookargs):
  1107.         addbase.__init__(self, fp)
  1108.         self.closehook = closehook
  1109.         self.hookargs = hookargs
  1110.  
  1111.     
  1112.     def close(self):
  1113.         addbase.close(self)
  1114.         if self.closehook:
  1115.             self.closehook(*self.hookargs)
  1116.             self.closehook = None
  1117.             self.hookargs = None
  1118.         
  1119.  
  1120.  
  1121.  
  1122. class addinfo(addbase):
  1123.     '''class to add an info() method to an open file.'''
  1124.     
  1125.     def __init__(self, fp, headers):
  1126.         addbase.__init__(self, fp)
  1127.         self.headers = headers
  1128.  
  1129.     
  1130.     def info(self):
  1131.         return self.headers
  1132.  
  1133.  
  1134.  
  1135. class addinfourl(addbase):
  1136.     '''class to add info() and geturl() methods to an open file.'''
  1137.     
  1138.     def __init__(self, fp, headers, url, code = None):
  1139.         addbase.__init__(self, fp)
  1140.         self.headers = headers
  1141.         self.url = url
  1142.         self.code = code
  1143.  
  1144.     
  1145.     def info(self):
  1146.         return self.headers
  1147.  
  1148.     
  1149.     def getcode(self):
  1150.         return self.code
  1151.  
  1152.     
  1153.     def geturl(self):
  1154.         return self.url
  1155.  
  1156.  
  1157.  
  1158. try:
  1159.     unicode
  1160. except NameError:
  1161.     
  1162.     def _is_unicode(x):
  1163.         return 0
  1164.  
  1165.  
  1166.  
  1167. def _is_unicode(x):
  1168.     return isinstance(x, unicode)
  1169.  
  1170.  
  1171. def toBytes(url):
  1172.     '''toBytes(u"URL") --> \'URL\'.'''
  1173.     if _is_unicode(url):
  1174.         
  1175.         try:
  1176.             url = url.encode('ASCII')
  1177.         except UnicodeError:
  1178.             raise UnicodeError('URL ' + repr(url) + ' contains non-ASCII characters')
  1179.         except:
  1180.             None<EXCEPTION MATCH>UnicodeError
  1181.         
  1182.  
  1183.     None<EXCEPTION MATCH>UnicodeError
  1184.     return url
  1185.  
  1186.  
  1187. def unwrap(url):
  1188.     """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
  1189.     url = url.strip()
  1190.     if url[:1] == '<' and url[-1:] == '>':
  1191.         url = url[1:-1].strip()
  1192.     
  1193.     if url[:4] == 'URL:':
  1194.         url = url[4:].strip()
  1195.     
  1196.     return url
  1197.  
  1198. _typeprog = None
  1199.  
  1200. def splittype(url):
  1201.     """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
  1202.     global _typeprog
  1203.     if _typeprog is None:
  1204.         import re
  1205.         _typeprog = re.compile('^([^/:]+):')
  1206.     
  1207.     match = _typeprog.match(url)
  1208.     if match:
  1209.         scheme = match.group(1)
  1210.         return (scheme.lower(), url[len(scheme) + 1:])
  1211.     return (None, url)
  1212.  
  1213. _hostprog = None
  1214.  
  1215. def splithost(url):
  1216.     """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
  1217.     global _hostprog
  1218.     if _hostprog is None:
  1219.         import re
  1220.         _hostprog = re.compile('^//([^/?]*)(.*)$')
  1221.     
  1222.     match = _hostprog.match(url)
  1223.     if match:
  1224.         return match.group(1, 2)
  1225.     return (None, url)
  1226.  
  1227. _userprog = None
  1228.  
  1229. def splituser(host):
  1230.     """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  1231.     global _userprog
  1232.     if _userprog is None:
  1233.         import re
  1234.         _userprog = re.compile('^(.*)@(.*)$')
  1235.     
  1236.     match = _userprog.match(host)
  1237.     if match:
  1238.         return map(unquote, match.group(1, 2))
  1239.     return (None, host)
  1240.  
  1241. _passwdprog = None
  1242.  
  1243. def splitpasswd(user):
  1244.     """splitpasswd('user:passwd') -> 'user', 'passwd'."""
  1245.     global _passwdprog
  1246.     if _passwdprog is None:
  1247.         import re
  1248.         _passwdprog = re.compile('^([^:]*):(.*)$')
  1249.     
  1250.     match = _passwdprog.match(user)
  1251.     if match:
  1252.         return match.group(1, 2)
  1253.     return (user, None)
  1254.  
  1255. _portprog = None
  1256.  
  1257. def splitport(host):
  1258.     """splitport('host:port') --> 'host', 'port'."""
  1259.     global _portprog
  1260.     if _portprog is None:
  1261.         import re
  1262.         _portprog = re.compile('^(.*):([0-9]+)$')
  1263.     
  1264.     match = _portprog.match(host)
  1265.     if match:
  1266.         return match.group(1, 2)
  1267.     return (host, None)
  1268.  
  1269. _nportprog = None
  1270.  
  1271. def splitnport(host, defport = -1):
  1272.     """Split host and port, returning numeric port.
  1273.     Return given default port if no ':' found; defaults to -1.
  1274.     Return numerical port if a valid number are found after ':'.
  1275.     Return None if ':' but not a valid number."""
  1276.     global _nportprog
  1277.     if _nportprog is None:
  1278.         import re
  1279.         _nportprog = re.compile('^(.*):(.*)$')
  1280.     
  1281.     match = _nportprog.match(host)
  1282.     if match:
  1283.         (host, port) = match.group(1, 2)
  1284.         
  1285.         try:
  1286.             if not port:
  1287.                 raise ValueError, 'no digits'
  1288.             port
  1289.             nport = int(port)
  1290.         except ValueError:
  1291.             nport = None
  1292.  
  1293.         return (host, nport)
  1294.     return (host, defport)
  1295.  
  1296. _queryprog = None
  1297.  
  1298. def splitquery(url):
  1299.     """splitquery('/path?query') --> '/path', 'query'."""
  1300.     global _queryprog
  1301.     if _queryprog is None:
  1302.         import re
  1303.         _queryprog = re.compile('^(.*)\\?([^?]*)$')
  1304.     
  1305.     match = _queryprog.match(url)
  1306.     if match:
  1307.         return match.group(1, 2)
  1308.     return (url, None)
  1309.  
  1310. _tagprog = None
  1311.  
  1312. def splittag(url):
  1313.     """splittag('/path#tag') --> '/path', 'tag'."""
  1314.     global _tagprog
  1315.     if _tagprog is None:
  1316.         import re
  1317.         _tagprog = re.compile('^(.*)#([^#]*)$')
  1318.     
  1319.     match = _tagprog.match(url)
  1320.     if match:
  1321.         return match.group(1, 2)
  1322.     return (url, None)
  1323.  
  1324.  
  1325. def splitattr(url):
  1326.     """splitattr('/path;attr1=value1;attr2=value2;...') ->
  1327.         '/path', ['attr1=value1', 'attr2=value2', ...]."""
  1328.     words = url.split(';')
  1329.     return (words[0], words[1:])
  1330.  
  1331. _valueprog = None
  1332.  
  1333. def splitvalue(attr):
  1334.     """splitvalue('attr=value') --> 'attr', 'value'."""
  1335.     global _valueprog
  1336.     if _valueprog is None:
  1337.         import re
  1338.         _valueprog = re.compile('^([^=]*)=(.*)$')
  1339.     
  1340.     match = _valueprog.match(attr)
  1341.     if match:
  1342.         return match.group(1, 2)
  1343.     return (attr, None)
  1344.  
  1345. _hextochr = dict((lambda .0: for i in .0:
  1346. ('%02x' % i, chr(i)))(range(256)))
  1347. _hextochr.update((lambda .0: for i in .0:
  1348. ('%02X' % i, chr(i)))(range(256)))
  1349.  
  1350. def unquote(s):
  1351.     """unquote('abc%20def') -> 'abc def'."""
  1352.     res = s.split('%')
  1353.     for i in xrange(1, len(res)):
  1354.         item = res[i]
  1355.         
  1356.         try:
  1357.             res[i] = _hextochr[item[:2]] + item[2:]
  1358.         continue
  1359.         except KeyError:
  1360.             res[i] = '%' + item
  1361.             continue
  1362.             except UnicodeDecodeError:
  1363.                 res[i] = unichr(int(item[:2], 16)) + item[2:]
  1364.                 continue
  1365.             
  1366.         return ''.join(res)
  1367.  
  1368.  
  1369.  
  1370. def unquote_plus(s):
  1371.     """unquote('%7e/abc+def') -> '~/abc def'"""
  1372.     s = s.replace('+', ' ')
  1373.     return unquote(s)
  1374.  
  1375. always_safe = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-'
  1376. _safemaps = { }
  1377.  
  1378. def quote(s, safe = '/'):
  1379.     '''quote(\'abc def\') -> \'abc%20def\'
  1380.  
  1381.     Each part of a URL, e.g. the path info, the query, etc., has a
  1382.     different set of reserved characters that must be quoted.
  1383.  
  1384.     RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
  1385.     the following reserved characters.
  1386.  
  1387.     reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  1388.                   "$" | ","
  1389.  
  1390.     Each of these characters is reserved in some component of a URL,
  1391.     but not necessarily in all of them.
  1392.  
  1393.     By default, the quote function is intended for quoting the path
  1394.     section of a URL.  Thus, it will not encode \'/\'.  This character
  1395.     is reserved, but in typical usage the quote function is being
  1396.     called on a path where the existing slash characters are used as
  1397.     reserved characters.
  1398.     '''
  1399.     cachekey = (safe, always_safe)
  1400.     
  1401.     try:
  1402.         safe_map = _safemaps[cachekey]
  1403.     except KeyError:
  1404.         safe += always_safe
  1405.         safe_map = { }
  1406.         for i in range(256):
  1407.             c = chr(i)
  1408.             if not c in safe or c:
  1409.                 pass
  1410.             safe_map[c] = '%%%02X' % i
  1411.         
  1412.         _safemaps[cachekey] = safe_map
  1413.  
  1414.     res = map(safe_map.__getitem__, s)
  1415.     return ''.join(res)
  1416.  
  1417.  
  1418. def quote_plus(s, safe = ''):
  1419.     """Quote the query fragment of a URL; replacing ' ' with '+'"""
  1420.     if ' ' in s:
  1421.         s = quote(s, safe + ' ')
  1422.         return s.replace(' ', '+')
  1423.     return quote(s, safe)
  1424.  
  1425.  
  1426. def urlencode(query, doseq = 0):
  1427.     '''Encode a sequence of two-element tuples or dictionary into a URL query string.
  1428.  
  1429.     If any values in the query arg are sequences and doseq is true, each
  1430.     sequence element is converted to a separate parameter.
  1431.  
  1432.     If the query arg is a sequence of two-element tuples, the order of the
  1433.     parameters in the output will match the order of parameters in the
  1434.     input.
  1435.     '''
  1436.     if hasattr(query, 'items'):
  1437.         query = query.items()
  1438.     else:
  1439.         
  1440.         try:
  1441.             if len(query) and not isinstance(query[0], tuple):
  1442.                 raise TypeError
  1443.             not isinstance(query[0], tuple)
  1444.         except TypeError:
  1445.             (ty, va, tb) = sys.exc_info()
  1446.             raise TypeError, 'not a valid non-string sequence or mapping object', tb
  1447.  
  1448.     l = []
  1449.     if not doseq:
  1450.         for k, v in query:
  1451.             k = quote_plus(str(k))
  1452.             v = quote_plus(str(v))
  1453.             l.append(k + '=' + v)
  1454.         
  1455.     else:
  1456.         for k, v in query:
  1457.             k = quote_plus(str(k))
  1458.             if isinstance(v, str):
  1459.                 v = quote_plus(v)
  1460.                 l.append(k + '=' + v)
  1461.                 continue
  1462.             if _is_unicode(v):
  1463.                 v = quote_plus(v.encode('ASCII', 'replace'))
  1464.                 l.append(k + '=' + v)
  1465.                 continue
  1466.             
  1467.             try:
  1468.                 x = len(v)
  1469.             except TypeError:
  1470.                 v = quote_plus(str(v))
  1471.                 l.append(k + '=' + v)
  1472.                 continue
  1473.  
  1474.             for elt in v:
  1475.                 l.append(k + '=' + quote_plus(str(elt)))
  1476.             
  1477.         
  1478.     return '&'.join(l)
  1479.  
  1480.  
  1481. def getproxies_environment():
  1482.     '''Return a dictionary of scheme -> proxy server URL mappings.
  1483.  
  1484.     Scan the environment for variables named <scheme>_proxy;
  1485.     this seems to be the standard convention.  If you need a
  1486.     different way, you can pass a proxies dictionary to the
  1487.     [Fancy]URLopener constructor.
  1488.  
  1489.     '''
  1490.     proxies = { }
  1491.     for name, value in os.environ.items():
  1492.         name = name.lower()
  1493.         if value and name[-6:] == '_proxy':
  1494.             proxies[name[:-6]] = value
  1495.             continue
  1496.     
  1497.     return proxies
  1498.  
  1499.  
  1500. def proxy_bypass_environment(host):
  1501.     """Test if proxies should not be used for a particular host.
  1502.  
  1503.     Checks the environment for a variable named no_proxy, which should
  1504.     be a list of DNS suffixes separated by commas, or '*' for all hosts.
  1505.     """
  1506.     if not os.environ.get('no_proxy', ''):
  1507.         pass
  1508.     no_proxy = os.environ.get('NO_PROXY', '')
  1509.     if no_proxy == '*':
  1510.         return 1
  1511.     (hostonly, port) = splitport(host)
  1512.     for name in no_proxy.split(','):
  1513.         if name:
  1514.             if hostonly.endswith(name) or host.endswith(name):
  1515.                 return 1
  1516.     return 0
  1517.  
  1518. if sys.platform == 'darwin':
  1519.     from _scproxy import _get_proxy_settings, _get_proxies
  1520.     
  1521.     def proxy_bypass_macosx_sysconf(host):
  1522.         """
  1523.         Return True iff this host shouldn't be accessed using a proxy
  1524.  
  1525.         This function uses the MacOSX framework SystemConfiguration
  1526.         to fetch the proxy information.
  1527.         """
  1528.         import re
  1529.         import socket
  1530.         fnmatch = fnmatch
  1531.         import fnmatch
  1532.         (hostonly, port) = splitport(host)
  1533.         
  1534.         def ip2num(ipAddr):
  1535.             parts = ipAddr.split('.')
  1536.             parts = map(int, parts)
  1537.             if len(parts) != 4:
  1538.                 parts = parts + [
  1539.                     0,
  1540.                     0,
  1541.                     0,
  1542.                     0][:4]
  1543.             
  1544.             return parts[0] << 24 | parts[1] << 16 | parts[2] << 8 | parts[3]
  1545.  
  1546.         proxy_settings = _get_proxy_settings()
  1547.         if '.' not in host:
  1548.             if proxy_settings['exclude_simple']:
  1549.                 return True
  1550.         
  1551.         hostIP = None
  1552.         for value in proxy_settings.get('exceptions', ()):
  1553.             if not value:
  1554.                 continue
  1555.             
  1556.             m = re.match('(\\d+(?:\\.\\d+)*)(/\\d+)?', value)
  1557.             if m is not None:
  1558.                 if hostIP is None:
  1559.                     
  1560.                     try:
  1561.                         hostIP = socket.gethostbyname(hostonly)
  1562.                         hostIP = ip2num(hostIP)
  1563.                     except socket.error:
  1564.                         continue
  1565.                     except:
  1566.                         None<EXCEPTION MATCH>socket.error
  1567.                     
  1568.  
  1569.                 None<EXCEPTION MATCH>socket.error
  1570.                 base = ip2num(m.group(1))
  1571.                 mask = int(m.group(2)[1:])
  1572.                 mask = 32 - mask
  1573.                 if hostIP >> mask == base >> mask:
  1574.                     return True
  1575.                 continue
  1576.             hostIP >> mask == base >> mask
  1577.             if fnmatch(host, value):
  1578.                 return True
  1579.         
  1580.         return False
  1581.  
  1582.     
  1583.     def getproxies_macosx_sysconf():
  1584.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1585.  
  1586.         This function uses the MacOSX framework SystemConfiguration
  1587.         to fetch the proxy information.
  1588.         '''
  1589.         return _get_proxies()
  1590.  
  1591.     
  1592.     def proxy_bypass(host):
  1593.         if getproxies_environment():
  1594.             return proxy_bypass_environment(host)
  1595.         return proxy_bypass_macosx_sysconf(host)
  1596.  
  1597.     
  1598.     def getproxies():
  1599.         if not getproxies_environment():
  1600.             pass
  1601.         return getproxies_macosx_sysconf()
  1602.  
  1603. elif os.name == 'nt':
  1604.     
  1605.     def getproxies_registry():
  1606.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1607.  
  1608.         Win32 uses the registry to store proxies.
  1609.  
  1610.         '''
  1611.         proxies = { }
  1612.         
  1613.         try:
  1614.             import _winreg as _winreg
  1615.         except ImportError:
  1616.             return proxies
  1617.  
  1618.         
  1619.         try:
  1620.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
  1621.             proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0]
  1622.             if proxyEnable:
  1623.                 proxyServer = str(_winreg.QueryValueEx(internetSettings, 'ProxyServer')[0])
  1624.                 if '=' in proxyServer:
  1625.                     for p in proxyServer.split(';'):
  1626.                         (protocol, address) = p.split('=', 1)
  1627.                         import re
  1628.                         if not re.match('^([^/:]+)://', address):
  1629.                             address = '%s://%s' % (protocol, address)
  1630.                         
  1631.                         proxies[protocol] = address
  1632.                     
  1633.                 elif proxyServer[:5] == 'http:':
  1634.                     proxies['http'] = proxyServer
  1635.                 else:
  1636.                     proxies['http'] = 'http://%s' % proxyServer
  1637.                     proxies['ftp'] = 'ftp://%s' % proxyServer
  1638.             
  1639.             internetSettings.Close()
  1640.         except (WindowsError, ValueError, TypeError):
  1641.             pass
  1642.  
  1643.         return proxies
  1644.  
  1645.     
  1646.     def getproxies():
  1647.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1648.  
  1649.         Returns settings gathered from the environment, if specified,
  1650.         or the registry.
  1651.  
  1652.         '''
  1653.         if not getproxies_environment():
  1654.             pass
  1655.         return getproxies_registry()
  1656.  
  1657.     
  1658.     def proxy_bypass_registry(host):
  1659.         
  1660.         try:
  1661.             import _winreg
  1662.             import re
  1663.         except ImportError:
  1664.             return 0
  1665.  
  1666.         
  1667.         try:
  1668.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
  1669.             proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0]
  1670.             proxyOverride = str(_winreg.QueryValueEx(internetSettings, 'ProxyOverride')[0])
  1671.         except WindowsError:
  1672.             return 0
  1673.  
  1674.         if not proxyEnable or not proxyOverride:
  1675.             return 0
  1676.         (rawHost, port) = splitport(host)
  1677.         host = [
  1678.             rawHost]
  1679.         
  1680.         try:
  1681.             addr = socket.gethostbyname(rawHost)
  1682.             if addr != rawHost:
  1683.                 host.append(addr)
  1684.         except socket.error:
  1685.             not proxyOverride
  1686.             not proxyOverride
  1687.         except:
  1688.             not proxyOverride
  1689.  
  1690.         
  1691.         try:
  1692.             fqdn = socket.getfqdn(rawHost)
  1693.             if fqdn != rawHost:
  1694.                 host.append(fqdn)
  1695.         except socket.error:
  1696.             not proxyOverride
  1697.             not proxyOverride
  1698.         except:
  1699.             not proxyOverride
  1700.  
  1701.         proxyOverride = proxyOverride.split(';')
  1702.         i = 0
  1703.         while i < len(proxyOverride):
  1704.             if proxyOverride[i] == '<local>':
  1705.                 proxyOverride[i:i + 1] = [
  1706.                     'localhost',
  1707.                     '127.0.0.1',
  1708.                     socket.gethostname(),
  1709.                     socket.gethostbyname(socket.gethostname())]
  1710.             
  1711.             i += 1
  1712.         for test in proxyOverride:
  1713.             test = test.replace('.', '\\.')
  1714.             test = test.replace('*', '.*')
  1715.             test = test.replace('?', '.')
  1716.             for val in host:
  1717.                 if re.match(test, val, re.I):
  1718.                     return 1
  1719.             
  1720.         
  1721.         return 0
  1722.  
  1723.     
  1724.     def proxy_bypass(host):
  1725.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1726.  
  1727.         Returns settings gathered from the environment, if specified,
  1728.         or the registry.
  1729.  
  1730.         '''
  1731.         if getproxies_environment():
  1732.             return proxy_bypass_environment(host)
  1733.         return proxy_bypass_registry(host)
  1734.  
  1735. else:
  1736.     getproxies = getproxies_environment
  1737.     proxy_bypass = proxy_bypass_environment
  1738.  
  1739. def test1():
  1740.     s = ''
  1741.     for i in range(256):
  1742.         s = s + chr(i)
  1743.     
  1744.     s = s * 4
  1745.     t0 = time.time()
  1746.     qs = quote(s)
  1747.     uqs = unquote(qs)
  1748.     t1 = time.time()
  1749.     if uqs != s:
  1750.         print 'Wrong!'
  1751.     
  1752.     print repr(s)
  1753.     print repr(qs)
  1754.     print repr(uqs)
  1755.     print round(t1 - t0, 3), 'sec'
  1756.  
  1757.  
  1758. def reporthook(blocknum, blocksize, totalsize):
  1759.     print 'Block number: %d, Block size: %d, Total size: %d' % (blocknum, blocksize, totalsize)
  1760.  
  1761.  
  1762. def test(args = []):
  1763.     if not args:
  1764.         args = [
  1765.             '/etc/passwd',
  1766.             'file:/etc/passwd',
  1767.             'file://localhost/etc/passwd',
  1768.             'ftp://ftp.gnu.org/pub/README',
  1769.             'http://www.python.org/index.html']
  1770.         if hasattr(URLopener, 'open_https'):
  1771.             args.append('https://synergy.as.cmu.edu/~geek/')
  1772.         
  1773.     
  1774.     
  1775.     try:
  1776.         for url in args:
  1777.             print '----------', url, '----------'
  1778.             (fn, h) = urlretrieve(url, None, reporthook)
  1779.             print fn
  1780.             if h:
  1781.                 print '======'
  1782.                 for k in h.keys():
  1783.                     print k + ':', h[k]
  1784.                 
  1785.                 print '======'
  1786.             
  1787.             fp = open(fn, 'rb')
  1788.             data = fp.read()
  1789.             del fp
  1790.             if '\r' in data:
  1791.                 table = string.maketrans('', '')
  1792.                 data = data.translate(table, '\r')
  1793.             
  1794.             print data
  1795.             (fn, h) = (None, None)
  1796.         
  1797.         print '-' * 40
  1798.     finally:
  1799.         urlcleanup()
  1800.  
  1801.  
  1802.  
  1803. def main():
  1804.     import getopt as getopt
  1805.     import sys
  1806.     
  1807.     try:
  1808.         (opts, args) = getopt.getopt(sys.argv[1:], 'th')
  1809.     except getopt.error:
  1810.         msg = None
  1811.         print msg
  1812.         print 'Use -h for help'
  1813.         return None
  1814.  
  1815.     t = 0
  1816.     for o, a in opts:
  1817.         if o == '-t':
  1818.             t = t + 1
  1819.         
  1820.         if o == '-h':
  1821.             print 'Usage: python urllib.py [-t] [url ...]'
  1822.             print '-t runs self-test;', 'otherwise, contents of urls are printed'
  1823.             return None
  1824.     
  1825.     if t:
  1826.         if t > 1:
  1827.             test1()
  1828.         
  1829.         test(args)
  1830.     elif not args:
  1831.         print 'Use -h for help'
  1832.     
  1833.     for url in args:
  1834.         print urlopen(url).read(),
  1835.     
  1836.  
  1837. if __name__ == '__main__':
  1838.     main()
  1839.  
  1840.